Skip to main content

Platform CLI 教程

本教程将指导您使用 Zapier Platform CLI 构建、测试并将一个示例应用程序推送到 Zapier。我们将使用一个模拟的食谱 API 进行演示,但对于生产环境的 Zapier 应用程序,您应连接到真实的 API。

先决条件

# 全局安装 CLI
npm install -g zapier-platform-cli

要查看 Platform CLI 中所有可用命令的列表,请运行 zapier help

  • 接下来,通过 CLI 进行身份验证。
# 使用部署密钥设置对 Zapier 平台的身份验证
zapier login

Zapier 会将您的部署密钥写入 ~/.zapierrc 文件。请妥善保管该文件,不要将其提交到源代码管理中。

1. 开始一个集成

使用 init 命令设置 所需的结构。系统会显示可用模板列表供您选择。

# 创建一个包含最小所需文件的目录并选择模板
zapier init example-app --template minimal
# 进入新目录
cd example-app

在该目录中,您会看到几个文件。package.json 是 Node.js 应用程序的标准依赖文件,已预填充了一些依赖项,其中最关键的是 zapier-platform-core,它使您的应用程序能够与 Zapier 平台集成。还有一个 index.js 文件和一个测试目录(稍后详述)。在继续之前,需要安装应用程序的依赖项:

npm install

index.js

index.js 是您的应用程序的入口点。Platform 会通过此文件了解您的应用程序如何与 Zapier 交互。在您选择的代码编辑器中打开刚创建的目录。

index.js 中,您可能会看到以下内容:

  • 一个单一的 module.exports 定义,由 Zapier 解析

  • triggers 用于描述从您的应用程序数据中触发事件的方式

  • searches 用于描述在您的应用程序中搜索数据的方式

  • creates 用于描述在您的应用程序中创建数据的方式

  • resources 是可选的,用于方便地描述 CRUD 类型的对象(请参阅 示例 resources 应用程序

  • beforeRequestafterResponse 是 HTTP 客户端的钩子,用于在每次调用中修改请求或响应

2. 添加一个触发器

添加一个 触发器,配置为从模拟 API 中读取数据:

zapier scaffold trigger recipe

scaffold 会创建一个新文件 recipe.js,位于 triggers 文件夹中。在构建自己的集成时,您可能会使用如 contact.jslead.jsorder.js 这样的文件名。

打开 triggers/recipe.js(由 zapier scaffold trigger recipe 创建的文件),并将其替换为:

const listRecipes = async (z, bundle) => {
const response = await z.request("http://57b20fb546b57d1100a3c405.mockapi.io/api/recipes");
return response.data;
};

module.exports = {
key: "recipe",
noun: "Recipe",
display: {
label: "New Recipe",
description: "Triggers when a new recipe is created.",
},
operation: {
perform: listRecipes,
sample: {
id: 1,
createdAt: 1472069465,
name: "Best Spaghetti Ever",
authorId: 1,
directions: "1. Boil Noodles\n2. Serve with sauce",
style: "italian",
},
},
};

要本地测试触发器,请运行 zapier invoke。命令会询问您要调用的操作。目前只有一个触发器 recipe,因此选择它。

$ zapier invoke
? Which action type would you like to invoke? trigger
? Which "trigger" key would you like to invoke? recipe
✔ Invoking triggers.recipe.operation.inputFields
✔ Invoking triggers.recipe.operation.perform
[{"id": "1","createdAt": 1471984289,"name": "name 1","authorId": 63,"directions": "directions 1","style": "style 1"},]

回顾代码:listRecipes 函数负责 API 操作,包括发出 HTTP 请求并返回解析后的响应数据。

在 JavaScript 中,async/await 是基于 Promises 的语法糖。请确保在调用异步函数时使用 await.then()

listRecipes 函数接收两个参数:z 对象和 bundle 对象。

  • Z 对象 包含处理 API 所需的一组实用工具。在示例中,我们使用 z.request 发出 HTTP 调用。

  • Bundle 对象 包含 API 调用所需的数据,如身份验证凭据或 POST 请求体。在示例中,未使用 Bundle,因为简单 GET 请求不需要这些。

虽然可以使用其他 Node.js 库实现相同功能,但优先使用 z 对象,因为它内置了增强 Zapier 体验的功能,如 HTTP 调用日志和错误处理。

module.exports 中,我们导出了元数据、listRecipes 函数和样本数据。Zapier 会使用这些元数据将其暴露给用户。当前,只需知道这些是定义触发器所需的最低信息。

此外,scaffold 命令还执行了以下操作:

index.js 文件现在包括:

const getRecipe = require('./triggers/recipe');
module.exports = {
// ...
triggers: {
[getRecipe.key]: getRecipe,
},
// ...
};

test/triggers 文件夹中,创建了 recipe.test.js 文件:

const App = require("../../index");
const appTester = zapier.createAppTester(App);

// 如果可用,将 .env 文件加载到环境中
zapier.tools.env.inject();

describe("triggers.recipe", () => {
it("should run", async () => {
const bundle = { inputData: {} };
const results = await appTester(App.triggers.recipe.operation.perform, bundle);
expect(results).toBeDefined();
// TODO: 添加更多断言
});
});

运行 zapier test 应能通过测试:

$ zapier test
Validating project locally
No structural errors found during validation routine.
This project is structurally sound!
✔ Running integration checks... 23 checks passed
Integration checks passed, no issues found.
Adding /Users/marinahand/.zapierrc to environment as ZAPIER_DEPLOY_KEY...
Running test suite with the following command: npm run --silent test --
PASS test/triggers/recipe.test.js
PASS test/triggers.test.js (7.52s)
Test Suites: 2 passed, 2 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 9.429s
Ran all test suites.

本示例仅使用一个测试,但您可以在 另一个示例应用程序 中查看多个测试。

3. 修改一个触发器

要让用户根据菜式风格过滤触发的食谱,请添加一个输入字段。

triggers/recipe.js 中,将文件替换为:

const listRecipes = async (z, bundle) => {
const params = {};
if (bundle.inputData.style) {
params.style = bundle.inputData.style;
}
const requestOptions = {
url: "http://57b20fb546b57d1100a3c405.mockapi.io/api/recipes",
params: params,
};
const response = await z.request(requestOptions);
return response.data;
};

module.exports = {
key: "recipe",
noun: "Recipe",
display: {
label: "New Recipe",
description: "Triggers when a new recipe is created.",
},
operation: {
inputFields: [
{
key: "style",
type: "string",
helpText: "Which styles of cuisine this should trigger on.",
required: false,
},
],
perform: listRecipes,
sample: {
id: 1,
createdAt: 1472069465,
name: "Best Spaghetti Ever",
authorId: 1,
directions: "1. Boil Noodles\n2. Serve with sauce",
style: "italian",
},
outputFields: [
{ key: "id", label: "ID" },
{ key: "createdAt", label: "Created At" },
{ key: "name", label: "Name" },
{ key: "directions", label: "Directions" },
{ key: "authorId", label: "Author ID" },
{ key: "style", label: "Style" },
],
},
};

注意,输入字段键 "style" 已添加到:

  • operation 中的 inputFields - 这定义了在 Zap 编辑器中显示的字段。该字段非必需,因此可为空。

  • listRecipes 函数中 - 使用 bundle.inputData.style 获取用户输入。

在本地开发中,重新运行 zapier invoke 以验证。跳过交互提示,直接指定参数:

$ zapier invoke trigger recipe --inputData '{"style":"style 20"}'
✔ Invoking triggers.recipe.operation.inputFields
✔ Invoking triggers.recipe.operation.perform
[{"id": "20","createdAt": 1578590011,"name": "name 20","authorId": 90,"directions": "directions 20","style": "style 20"}]

修改测试:在 test/triggers 中,将 recipe.test.js 替换为:

const zapier = require("zapier-platform-core");
const App = require("../../index");
const appTester = zapier.createAppTester(App);

describe("triggers", () => {
describe("new recipe trigger", () => {
it("should load recipes", async () => {
const bundle = {
inputData: {
style: "style 2",
},
};
const results = await appTester(App.triggers.recipe.operation.perform, bundle);
expect(results.length).toBeGreaterThan(1);
const firstRecipe = results[0];
expect(firstRecipe.name).toEqual("name 2");
expect(firstRecipe.directions).toEqual("directions 2");
});

it("should load recipes without filters", async () => {
const bundle = {};
const results = await appTester(App.triggers.recipe.operation.perform, bundle);
expect(results.length).toBeGreaterThan(1);
const firstRecipe = results[0];
expect(firstRecipe.name).toEqual("name 1");
expect(firstRecipe.directions).toEqual("directions 1");
});
});
});

运行测试以确认:

zapier test

4. 部署一个集成

将本地应用程序集成推送到 Zapier,以便在 Zap 中使用。

您可以管理多个版本,便于处理重大更改和测试。目前,推送一个版本。

首次推送需要注册应用程序。运行 zapier register,并按照提示提供名称和详情。然后,使用 zapier push 推送:

$ zapier push
✔ Copying project to temp directory
✔ Installing project dependencies
✔ Applying entry point file
✔ Building app definition.json
✔ Validating project schema and style
✔ Zipping project and dependencies
✔ Testing build
✔ Cleaning up temp directory
✔ Uploading version 1.0.0
Push complete! Built build/build.zip and build/source.zip and uploaded them to Zapier.

登录 Zap 编辑器,使用新集成创建 Zap。

在触发器步骤中,选择您的应用程序和“New Recipe”触发器,您会看到定义的标签和描述。

在 Zap 编辑器中,填写“style”输入字段。运行测试时,listRecipes 函数会执行 API 请求并返回结果。

使用 zapier logs --type http 查看请求:

$ zapier logs --type http
The logs of your app "Example App" listed below.
┌────────┬────────┬────────────────────────────────────────────────────────┬───────────────┬─────────┬──────────────────────────────────────┬───────────────────────────┐
│ Status │ Method │ URL │ Querystring │ Version │ Step │ Timestamp │
├────────┼────────┼────────────────────────────────────────────────────────┼───────────────┼─────────┼──────────────────────────────────────┼───────────────────────────┤
│ 200 │ GET │ http://57b20fb546b57d1100a3c405.mockapi.io/api/recipes │ style=italian │ 1.0.0 │ a9055e16-fc0d-4fb2-a3e6-9d442d1f70e8 │ 2016-09-13T15:11:30-05:00 │
└────────┴────────┴────────────────────────────────────────────────────────┴───────────────┴─────────┴──────────────────────────────────────┴───────────────────────────┘
Most recent logs near the bottom.

5. 添加认证

认证是与大多数 API 交互的关键。Zapier 支持多种 认证方案。本示例使用 API 密钥添加标头认证。

查看示例应用程序了解不同类型:

Session Auth

Digest Auth

index.js 中,为示例应用程序添加 authentication 部分:

authentication: {
type: 'custom',
fields: [{ key: 'apiKey', type: 'string' }],
test: async (z, bundle) => {
const response = await z.request('http://57b20fb546b57d1100a3c405.mockapi.io/api/me');
return response.data;
},
},

以上定义了 authentication 的必需属性:

  • fields 定义认证字段,类似于触发器的 inputFields。用户连接账户时会提示输入,值可用在 bundle.authData 中。

  • test 函数用于验证凭据,通过发出认证请求判断有效性。如果有效,返回任何内容;无效时抛出错误。

确保 API 密钥包含在所有请求中。在 index.js 中添加:

const addApiKeyToHeader = (request, z, bundle) => {
request.headers["My-Auth-Header"] = bundle.authData.apiKey;
return request;
};

并在 module.exports 中添加:

beforeRequest: [addApiKeyToHeader],

初始化并测试认证:

$ zapier invoke auth start
The .env file does not exist or is empty. You may need to set some environment variables in there if your code uses process.env.
? apiKey | string: mock-api-key
Auth data appended to .env file. Run `zapier invoke auth test` to test it.

$ zapier invoke auth test
✔ Invoking authentication.test
[{"id": "1","createdAt": 1473801403,"userName": "userName 1"}]

重新推送:

zapier push

在 Zap 中,触发器会显示“Account”选项。添加账户后,Zapier 会验证凭据。

查看日志确认:

$ zapier logs --type http --detailed --limit=1
The logs of your app "Example App" listed below.
┌─────────────────────┬────────────────────────────────────────────────────────────────────────────────────────┐
│ Status │ 200 │
│ Method │ GET │
│ URL │ http://57b20fb546b57d1100a3c405.mockapi.io/api/me │
│ Querystring │ │
│ Version │ 1.0.0 │
│ Step │ │
│ Timestamp │ 2016-09-16T15:57:51-05:00 │
│ Request Headers │ user-agent: Zapier │
│ │ My-Auth-Header: :censored:6:b1af149262: │
│ Request Body │ │
│ Response Headers │ server: Cowboy │
│ │ connection: close │
│ │ x-powered-by: Express │
│ │ access-control-allow-origin: * │
│ │ access-control-allow-methods: GET,PUT,POST,DELETE,OPTIONS │
│ │ access-control-allow-headers: X-Requested-With,Content-Type,Cache-Control,access_token │
│ │ content-type: application/json │
│ │ content-length: 59 │
│ │ etag: "-80491811" │
│ │ vary: Accept-Encoding │
│ │ date: Fri, 16 Sep 2016 20:57:51 GMT │
│ │ via: 1.1 vegur │
│ Response Body │ [{"id":"1","createdAt":1473801403,"userName":"userName 1"}] │
└─────────────────────┴────────────────────────────────────────────────────────────────────────────────────────┘

6. 邀请团队成员管理集成

分享集成至团队开发者的 开发者仪表板

运行:

  • zapier team:add user@example.com admin 邀请管理员。

  • zapier team:add user@example.com collaborator 邀请协作者。

替换示例电子邮件。

7. 与用户分享集成

拥有触发器或操作后,邀请用户测试。

运行 zapier users:add user@example.com 1.0.0 发送邀请。

或者,使用 zapier users:links 获取分享链接。

8. 修改集成

对集成进行更改时,使用 新版本

某些集成需新版本编辑。建议始终使用新版本,并遵循 Zapier 最佳实践

Platform CLI 创建的集成无法在 UI 中编辑。

在 UI 中可管理:

  • 邀请团队

  • 监控使用

  • 提交公开

  • 推广版本

  • 迁移用户

了解更多

需要帮助?联系我们